package JUC.pc;

/**
 * synchronized 版本
 * 线程之间的通信问题  等待通知，通知唤醒
 * 线程交替执行，A,B操作同一变量 num = 0
 * A num+1
 * B num-1
 * 判断时不能用if!!!会造成虚假唤醒
 */
public class A {
    public static void main(String[] args) {
        Date date = new Date();

        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                try {
                    date.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();


        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                try {
                    date.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();

    }
}

//判断等待，业务，通知
class Date { //数字   资源类
    private int number = 0;

    //+1 如果当前数字不等于0，可以进行加一操作
    public synchronized void increment() throws InterruptedException {
       while (number != 0) {
            //等待
            this.wait();
        }
        //0->1
        number++;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        //通知其他线程+1完毕
        this.notify();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            //等待
            this.wait();
        }
        //1->0
        number--;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        //通知其他线程-1完毕
        this.notify();
    }

}